package com.aaa.member.service.impl;

import com.aaa.common.bo.Car;
import com.aaa.common.bo.CouponHistory;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnCode;
import com.aaa.common.constants.ServiceCostant;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.common.vo.Order;
import com.aaa.member.entity.AccountStatement;
import com.aaa.member.entity.Client;
import com.aaa.member.entity.IntegrationHistory;
import com.aaa.member.entity.MemberLevel;
import com.aaa.member.mapper.AccountStatementMapper;
import com.aaa.member.mapper.OrderDao;
import com.aaa.member.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Order)表服务实现类
 *
 * @author pyy
 * @since 2020-11-17 20:06:34
 */
@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    /**
     * 依赖注入流水服务
     */
    @Autowired
    private AccountStatementService accountStatementService;
    /**
     * 依赖注入历史积分服务
     */
    @Autowired
    private IntegrationHistoryService integrationHistoryService;
    /**
     * 依赖注入优惠券历史服务
     */
    @Autowired
    private CouponService couponService;
    /**
     * 依赖注入车辆服务
     */
    @Autowired
    private CarService carService;
    /**
     * 依赖注入会员服务
     */
    @Autowired
    private ClientService clientService;
    /**
     * 依赖注入会员服务
     */
    @Autowired
    private MemberLevelService memberLevelService;


    /**
     * 通过选车地址选车
     *
     * @param map
     * @return
     */
    @Override
    public List<Map> selectCarByAddress(Map map) {
        return orderDao.selectCarByAddress(map);
    }

    /**
     * 根据订单id显示订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Map selectOrderDetail(Integer id) {
        return orderDao.selectOrderDetail(id);
    }

    /**
     * 通过用户id订单状态展示订单列表
     * 订单状态（输入Entered：1，提交Booked：2，预约Reserved：3，使用中Inuse：4，交还Returned：5，取消Cancelled：6）
     *
     * @param order
     * @return
     */
    @Override
    public List<Map> queryAll(Order order) {
        return orderDao.queryAll(order);
    }

    /**
     * 通过用户id订单状态展示订单列表
     *
     * @param order
     * @return
     */
    @Override
    public Result queryAllByParam(Integer pageNo, Integer pageSize, Order order) {
        if (pageNo == 0 || pageSize == 0) {
            throw new CustomException(ExceptionConstant.INVALID_ARGUMENT.getErrorCode(),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage());
        }
        PageHelper.startPage(pageNo, pageSize);
        List<Map> list = orderDao.queryAllByParam(order);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map map : list) {
            map.put("start_time", simpleDateFormat.format(map.get("start_time")));
            map.put("end_time", simpleDateFormat.format(map.get("end_time")));
            map.put("addtime", simpleDateFormat.format(map.get("addtime")));
        }
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        return new Result<>(ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getMsg(), pageInfo);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer id) {
        return this.orderDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Order> queryAllByLimit(int offset, int limit) {
        return this.orderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order insert(Order order) {
        //实例化当前时间
        Date currentDate = new Date();
       /* Car rentCar = carService.selectOne(order.getCarId());
        //获取租车价钱 
        Object price = rentCar.getPrice();
        //计算日期
        Date startTime = order.getStartTime();
        Date endTime = order.getEndTime();
        //获取1970午夜到现在的毫秒
        long stime = startTime.getTime();
        long etime = endTime.getTime();
        //相减
        double days = (etime - stime) / 1000 / 3600 / 24;
        int tdyas = (int)days;
        int totalDay =  tdyas+((tdyas-days)>0.5?1:0);
        double  totalPrice =  Double.valueOf(price.toString())*totalDay;*/
        //再加其他费用
        this.orderDao.insert(order);
        //计算消费金额，更新订单总金额
        Double totalPrice = order.getTotalPrice();
        System.out.println("总金额===" + totalPrice);
        //获取该用户优惠券的，添加客户优惠券关联表
        Map paramMap = new HashMap();
        paramMap.put("memberId", order.getClientId());
        paramMap.put("shopId", order.getBrrowShop());
        Result result = couponService.queryAllInOrder(paramMap);
        Object data = result.getData();
        double tempAmount = 0;
        if (data != null) {
            List<Map> couponMapList = (List<Map>) data;
            CouponHistory couponHistory = null;
            for (Map map : couponMapList) {
                //3张
                tempAmount += Double.valueOf(map.get("amount") + "");
                couponHistory = new CouponHistory();
                couponHistory.setId(Long.valueOf(map.get("id") + ""));
                couponHistory.setOrderId(Long.valueOf(order.getId()));
                couponHistory.setUseStatus(0);
                couponHistory.setUseTime(currentDate);
                couponHistory.setOrderSn(order.getOrderNo());
                couponService.update(couponHistory);
            }
        }
        //减去优惠券金额
        double endAmount = totalPrice - tempAmount;
        System.out.println("优惠券金额===" + tempAmount);
        //更新订单实际金额
        order.setTotalPrice(endAmount);
        orderDao.update(order);

        //向账号流水表添加数据
        AccountStatement accountStatement = new AccountStatement();
        accountStatement.setAmount(endAmount);
        accountStatement.setAddtime(currentDate);
        accountStatement.setClientId(order.getClientId());
        accountStatement.setTypeId(ServiceCostant.AccountStatementType.PAY);
        accountStatement.setPayId(order.getPayType());
        accountStatementService.insert(accountStatement);
        //计算积分，添加客户积分历史表，更新成长值，更新客户积分和历史积分，账户余额，更新会员等级
        Result clientResult = clientService.queryById(order.getClientId());
        Client client = (Client) clientResult.getData();
        //更新账户余额
        client.setAccountBalance(client.getAccountBalance() - endAmount);
        //当前客户成长值
        double currentGrowth = client.getGrowth() + endAmount;
        //更新成长值
        client.setGrowth(currentGrowth);
        //根据用户级别ID查询用户级别
        MemberLevel memberLevel = memberLevelService.queryById(Long.valueOf(client.getMemberLevelId().toString()));
        double currentIntegration = 0;
        if (memberLevel != null) {
            Double ratio = memberLevel.getRatio();
            currentIntegration = endAmount * ratio;
        }
        //更新积分
        client.setIntegration((int) (client.getIntegration() + currentIntegration));
        //更新历史积分
        client.setHistoryIntegration((int) (client.getHistoryIntegration() + currentIntegration));
        //获取会员等级
        List<MemberLevel> memberLevels = memberLevelService.queryAll(null);
        //判断加完成长值的等级变化
        if (memberLevels != null && memberLevels.size() > 0) {
            for (MemberLevel level : memberLevels) {
                if (currentGrowth < level.getGrowthPoint()) {
                    //更新会员等级
                    client.setMemberLevelId(Integer.valueOf(level.getId() + ""));
                    break;
                }
            }
        }
        clientService.update(client);

        //添加客户积分历史表
        IntegrationHistory integrationHistory = new IntegrationHistory();
        integrationHistory.setMemberId(Long.valueOf(order.getClientId()));
        integrationHistory.setCreateTime(currentDate);
        integrationHistory.setChangeType(ServiceCostant.IntegrationChangeType.INCR);
        integrationHistory.setChangeCount((int) currentIntegration);
        System.out.println("添加客户积分===" + integrationHistory.getChangeCount());
        integrationHistory.setOperateMan(client.getName());
        integrationHistory.setOperateNote("消费积分");
        integrationHistory.setSourceType(0);
        integrationHistoryService.insert(integrationHistory);
        //更新车辆状态
        Car car = new Car();
        car.setId(order.getCarId());
        car.setState(ServiceCostant.CarStatus.RENTED);
        carService.update(car);
        return order;
    }

    /**
     * 修改订单id修改订单当前状态为已取消或者还车
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update(order);
        if (order.getState() == 5 || order.getState() == 6) {
            //更新车辆状态
            Car car = new Car();
            car.setId(order.getCarId());
            car.setState(ServiceCostant.CarStatus.ENABLEUSE);
            carService.update(car);
            System.out.println(car.getId());
            System.out.println(car.getState());
        }
        return this.queryById(order.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderDao.deleteById(id) > 0;
    }
}